package com.hengxinguotong.zhihuichengjian.ui.device;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.hengxinguotong.zhihuichengjian.R;
import com.hengxinguotong.zhihuichengjian.adapter.AualityTestAddPicAdapter;
import com.hengxinguotong.zhihuichengjian.ui.app.BaseFragment;
import com.hengxinguotong.zhihuichengjian.bean.Device;
import com.hengxinguotong.zhihuichengjian.bean.DeviceListRes;
import com.hengxinguotong.zhihuichengjian.bean.User;
import com.hengxinguotong.zhihuichengjian.picturebrowser.view.TaskBigImgActivity;
import com.hengxinguotong.zhihuichengjian.ui.BaseActivity;
import com.hengxinguotong.zhihuichengjian.ui.PersonLiableListActivity;
import com.hengxinguotong.zhihuichengjian.ui.ScanningActivity;
import com.hengxinguotong.zhihuichengjian.utils.FileUtil;
import com.hengxinguotong.zhihuichengjian.utils.SPUtil;
import com.hengxinguotong.zhihuichengjian.utils.Utils;
import com.hengxinguotong.zhihuichengjian.widget.font.HXEditTextView;
import com.hengxinguotong.zhihuichengjian.widget.font.HXTextView;
import com.lidroid.xutils.http.RequestParams;

import org.apache.http.entity.StringEntity;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import me.nereo.multi_image_selector.MultiImageSelector;
import me.nereo.multi_image_selector.MultiImageSelectorActivity;

/**
 * Created by Administrator on 2017/3/13.
 */

public class DeviceFragment extends BaseFragment implements AualityTestAddPicAdapter.OnRecyclerViewClickListener {
    @BindView(R.id.select_ll)
    LinearLayout selectLl;
    @BindView(R.id.scan_iv)
    ImageView scanIv;
    @BindView(R.id.name_etv)
    HXEditTextView nameEtv;
    @BindView(R.id.number_etv)
    HXEditTextView numberEtv;
    @BindView(R.id.position_rl)
    RelativeLayout positionRl;
    @BindView(R.id.model_etv)
    HXEditTextView modelEtv;
    @BindView(R.id.profession_rl)
    RelativeLayout professionRl;
    @BindView(R.id.manufactor_etv)
    HXEditTextView manufactorEtv;
    @BindView(R.id.leasing_company_etv)
    HXEditTextView leasingCompanyEtv;
    @BindView(R.id.person_liable_etv)
    HXTextView personLiableEtv;
    @BindView(R.id.no_pic_tv)
    HXTextView noPicTv;
    @BindView(R.id.add_pic_rv)
    RecyclerView addPicRv;
    @BindView(R.id.remarks_etv)
    HXEditTextView remarksEtv;
    Unbinder unbinder;

    private AualityTestAddPicAdapter addPicAdapter;
    private List<String> paths;
    private List<String> minPaths;
    private String deviceId;  //设备id  扫描时获得
    private String personLiableId; //责任人id
    private String personLiableName; //责任人
    private BaseActivity baseActivity;
    private final int SELECTPERSON = 1001;
    private final int GETCODE = 1002;
    private final int GETDEVICE = 1003;
    private Device device;
    private String type;//类型.1:进场;2:出场

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View contentView = inflater.inflate(R.layout.fragment_device, null);
        baseActivity = (BaseActivity) getActivity();
        unbinder = ButterKnife.bind(this, contentView);
        type = (String) getArguments().get("type");
        initView();
        return contentView;
    }

    @Override
    public void onLazyLoad() {
    }

    private void initView() {
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
        paths = new ArrayList<String>();
        paths.add(Utils.ADDPIC);
        addPicAdapter = new AualityTestAddPicAdapter(getActivity(), paths, this, true);
        addPicRv.setLayoutManager(linearLayoutManager);
        addPicRv.setAdapter(addPicAdapter);
        if (device != null) {
            selectLl.setVisibility(View.GONE);
            Utils.setEditTextViewUnable(device.getName(),nameEtv);
            Utils.setEditTextViewUnable(device.getNumber(),numberEtv);
            Utils.setEditTextViewUnable(device.getModel(),modelEtv);
            Utils.setEditTextViewUnable(device.getManufacturer(),manufactorEtv);
            Utils.setEditTextViewUnable(device.getLeasingCompany(),leasingCompanyEtv);
            Utils.setEditTextViewUnable(device.getRemark(),remarksEtv);


            personLiableEtv.setText(device.getUserName());
            personLiableEtv.setClickable(false);

            paths = device.getPicList();
            if (paths.size() == 0) {
                noPicTv.setVisibility(View.VISIBLE);
                addPicRv.setVisibility(View.GONE);
            } else {
                addPicAdapter =new AualityTestAddPicAdapter(getActivity(), paths, this, false);
                addPicRv.setAdapter(addPicAdapter);
            }

            remarksEtv.setText(device.getRemark());
            remarksEtv.setEnabled(false);
        }
    }

    public static DeviceFragment newInstance(String type) {
        DeviceFragment fragment = new DeviceFragment();
        Bundle args = new Bundle();
        args.putString("type", type);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @Override
    public void onItemClick(View v, int position) {
        Intent intent;
        if (paths.get(position).equals(Utils.ADDPIC)) {
            List<String> tempStrings = new ArrayList<String>();
            tempStrings.addAll(paths);
            tempStrings.remove(tempStrings.size() - 1);
            MultiImageSelector.create()
                    .showCamera(true) // show camera or not. true by default_grey
                    .count(9) // max select image size, 9 by default_grey. used width #.multi()
                    .multi()
                    .origin((ArrayList<String>) tempStrings)
                    .start(this, 1);
        } else {
            if (device!=null) {
                TaskBigImgActivity.startActivity(getActivity(), (ArrayList<String>) paths, position);
            } else {
                paths.remove(position);
                addPicAdapter.notifyDataSetChanged();
            }
        }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(data != null){
            if (requestCode == 1) {
                paths = data.getStringArrayListExtra(MultiImageSelectorActivity.EXTRA_RESULT);
                paths.add(Utils.ADDPIC);
                if (addPicAdapter != null) {
                    addPicAdapter.setPaths(paths);
                }
            } else if (requestCode == SELECTPERSON) {
                User user = (User) data.getSerializableExtra("selectUser");
//                personLiableId = temp.get(0).getPersonId();
                personLiableId = user.getUserId();
                personLiableName = user.getName();
                personLiableEtv.setText(personLiableName);
            } else if (requestCode == GETCODE) {
//            String code = data.getStringExtra("code");
//            if (code.contains("_")) {
//                deviceId = code.split("_")[1];
//                getDeviceInfo(getResources().getString(R.string.loading));
//            }
                String QRcode = data.getStringExtra("QRcode");
                if(QRcode.contains("_")){
                    deviceId = QRcode.split("_")[1];
                }else{
                    deviceId = QRcode;
                }
                numberEtv.setText(QRcode);
                getDeviceInfo(getResources().getString(R.string.loading));
            } else if (requestCode == GETDEVICE) {
                device = (Device) data.getExtras().get("device");
                deviceId = device.getId();
                reloadViews(device);
            }
        }
    }


    public void setData(Device device) {
        this.device = device;
    }


    private void getDeviceInfo(String alert) {
        JSONObject jsonObject = new JSONObject();

        try {
            jsonObject.put("equipmentId", deviceId);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestParams params = new RequestParams();
        params.addHeader("Content-type", "application/json");
        try {
            params.setBodyEntity(new StringEntity(jsonObject.toString(), "UTF-8"));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        Utils.requestData(alert, baseActivity, "/equipmentRegister/queryList/" + SPUtil.getString(getActivity(),"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
                    Gson gson = new Gson();
                    DeviceListRes deviceListRes = gson.fromJson(json, DeviceListRes.class);
                    if(deviceListRes.getValue().size()==0){
                        deviceId=null;
                        return;
                    }

                    if (deviceListRes.getValue().size() == 1) {
                        reloadViews(deviceListRes.getValue().get(0));
                    }
                }

            }

            @Override
            public void onFailure(String json) {
                deviceId=null;
            }
        });
    }


    private void reloadViews(Device device) {
        if(Utils.isEmpty(device.getName())){
            deviceId=null;
            return;
        }
        nameEtv.setText(device.getName());
        numberEtv.setText(device.getNumber());
        modelEtv.setText(device.getModel());
        manufactorEtv.setText(device.getManufacturer());
        leasingCompanyEtv.setText(device.getLeasingCompany());
    }

    private boolean checkText() {
        if (Utils.isEmpty(nameEtv.getEditableText().toString())) {
            baseActivity.showToast("请输入设备名称");
            return false;
        }

        if (Utils.isEmpty(personLiableId)) {
            baseActivity.showToast("请选择责任人");
            return false;
        }

        return true;
    }


    public void getMinImage(final String type) {
        if (!checkText()) {
            return;
        }

        if (paths.size() > 1) {
            Utils.startDownload(getResources().getString(R.string.loading), baseActivity);

            new AsyncTask<Void, Void, Void>() {
                @Override
                protected Void doInBackground(Void... voids) {
                    minPaths = new ArrayList<String>();
                    for (int i = 0; i < paths.size() - 1; i++) {
                        String path = FileUtil.imageDir1 + System.currentTimeMillis() + ".jpg";
                        FileUtil.writeByteArrayToPath(path, FileUtil.handleUploadImg(paths.get(i)));
                        minPaths.add(path);
                    }
                    return null;
                }


                @Override
                protected void onPostExecute(Void aVoid) {
                    deviceInorOut(type);
                }


            }.execute();
        } else {
            minPaths = new ArrayList<String>();
            deviceInorOut(type);
        }

    }

    private void deviceInorOut(final String type) {
        RequestParams params = new RequestParams();
        if (!Utils.isEmpty(deviceId)) {
            params.addBodyParameter("equipmentId", deviceId);
        }
        params.addBodyParameter("constructionId",  SPUtil.getString(getActivity(),"constructionid"));
        params.addBodyParameter("name", nameEtv.getEditableText().toString());
        params.addBodyParameter("number", numberEtv.getEditableText().toString());
        params.addBodyParameter("model", modelEtv.getEditableText().toString());
        params.addBodyParameter("manufacturer", manufactorEtv.getEditableText().toString());
        params.addBodyParameter("leasingCompany", leasingCompanyEtv.getEditableText().toString());
        params.addBodyParameter("createBy", SPUtil.getString(getActivity(), "userId"));
        params.addBodyParameter("personId", personLiableId);
        params.addBodyParameter("remark", remarksEtv.getEditableText().toString());
        for (int i = 0; i < minPaths.size(); i++) {
            params.addBodyParameter("files[" + i + "]", new File(minPaths.get(i)));
        }
        params.addBodyParameter("type", type);


        Utils.requestData(getResources().getString(R.string.loading), getActivity(), "/equipmentRegister/saveUpdate/" + SPUtil.getString(getActivity(),"uuid"), params, new Utils.ListenerJson() {
            @Override
            public void onSuccess(String json) {
                if (!Utils.isEmpty(json)) {
//                    Gson gson = new Gson();
//                    if (Utils.isEmpty(deviceId)) {
//                        Device device = new Device();
//                        DeviceInRes deviceInRes = gson.fromJson(json, DeviceInRes.class);
//                        Intent intent = new Intent(getActivity(), QRCodeActivity.class);
//                        device.setId(deviceInRes.getValue());
//                        device.setLeasingCompany(leasingCompanyEtv.getEditableText().toString());
//                        device.setManufacturer(manufactorEtv.getEditableText().toString());
//                        device.setModel(modelEtv.getEditableText().toString());
//                        device.setName(nameEtv.getEditableText().toString());
//                        device.setUserName(personLiableName);
//                        intent.putExtra("device", device);
//                        startActivity(intent);
//                    } else {
                    baseActivity.showToast("提交成功");
//                        getActivity().getIntent().putExtra("type", type);
                    getActivity().setResult(1);
//                    }
                    getActivity().finish();
                }
            }

            @Override
            public void onFailure(String json) {

            }
        });
    }

    @OnClick({ R.id.scan_iv, R.id.person_liable_etv, R.id.scan_rl, R.id.list_rl})
    public void onClick(View view) {
        Intent intent;
        switch (view.getId()) {
            case R.id.scan_rl:
            case R.id.scan_iv:
//                intent = new Intent(getActivity(), CaptureActivity.class);
                intent = new Intent(getActivity(), ScanningActivity.class);
                startActivityForResult(intent, GETCODE);
                break;
            case R.id.list_rl:
                intent = new Intent(getActivity(), DeviceSelectedActivity.class);
                startActivityForResult(intent, GETDEVICE);
                break;
            case R.id.person_liable_etv:
                intent = new Intent(getActivity(), PersonLiableListActivity.class);
                intent.putExtra("type", 0);
                startActivityForResult(intent, SELECTPERSON);
                break;
        }
    }
}
